package com.zy.composeworld.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.zy.composeworld.R
import com.zy.composeworld.utils.ZLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.reflect.ParameterizedType

abstract class BaseVBFragment<VB : ViewBinding> : BaseFragment() {
    protected var stepOne = 0f
    protected var widthPixels = 0f
    protected var heightPixels = 0f

    protected lateinit var binding: VB

    open val TAG: String = this::class.java.simpleName

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initDimen()

        //_binding = getViewBinding()
        (javaClass.genericSuperclass as ParameterizedType).let {
            it.actualTypeArguments.let { types ->
                binding =
                    (types[0] as Class<VB>).getMethod("inflate", LayoutInflater::class.java)
                        .invoke(null, layoutInflater) as VB
            }
        }
        binding.initViewBinding()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return binding.root
    }

    abstract fun VB.initViewBinding()

    private fun initDimen() {
        val displayMetrics = resources.displayMetrics
        widthPixels = displayMetrics.widthPixels.toFloat()
        heightPixels = displayMetrics.heightPixels.toFloat()
        val dp_16 = resources.getDimension(R.dimen.dp_16)
        ZLog.d(TAG, "displayMetrics:$displayMetrics")
        ZLog.d(TAG, "heightPixels:$heightPixels")
        ZLog.d(TAG, "widthPixels:$widthPixels")
        ZLog.d(TAG, "dp_8:$dp_16")
        stepOne = (widthPixels - dp_16) / 10
        ZLog.d(TAG, "stepOne:$stepOne")
    }

    protected fun mainRunPost(long: Long, run: Runnable) {
        lifecycleScope.launch(Dispatchers.Main) {
            delay(long)
            run.run()
        }
    }

    protected fun mainRunPost(run: Runnable) {
        mainRunPost(0, run)
    }
}